package com.lei.springbootpractice.service;

import com.lei.springbootpractice.dao.NotificationStatusMapper;
import com.lei.springbootpractice.pojo.NotificationStatusPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class NotificationService {

    @Autowired
    private NotificationStatusMapper notificationMapper;

    /**
     * 获取用户未读通知数量
     */
    public int getUnreadCount(String userId) {
        try {
            return notificationMapper.getUnreadCount(userId);
        } catch (Exception e) {
            System.err.println("获取未读通知数量失败: " + e.getMessage());
            return 0;
        }
    }

    /**
     * 获取用户未读通知列表
     */
    public List<NotificationStatusPojo> getUnreadNotifications(String userId, int limit) {
        try {
            return notificationMapper.getUnreadNotifications(userId, limit);
        } catch (Exception e) {
            System.err.println("获取未读通知列表失败: " + e.getMessage());
            return List.of();
        }
    }

    /**
     * 获取用户最新通知列表
     */
    public List<NotificationStatusPojo> getLatestNotifications(String userId, int limit) {
        try {
            return notificationMapper.getLatestNotifications(userId, limit);
        } catch (Exception e) {
            System.err.println("获取最新通知列表失败: " + e.getMessage());
            return List.of();
        }
    }

    /**
     * 标记指定通知为已读
     */
    public boolean markAsRead(Integer notificationId) {
        try {
            return notificationMapper.markAsRead(notificationId) > 0;
        } catch (Exception e) {
            System.err.println("标记通知已读失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 标记用户所有通知为已读
     */
    public boolean markAllAsRead(String userId) {
        try {
            return notificationMapper.markAllAsRead(userId) >= 0;
        } catch (Exception e) {
            System.err.println("标记所有通知已读失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 标记用户特定类型的通知为已读
     */
    public boolean markTypeAsRead(String userId, String notificationType) {
        try {
            return notificationMapper.markTypeAsRead(userId, notificationType) >= 0;
        } catch (Exception e) {
            System.err.println("标记特定类型通知已读失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 标记用户特定对话的通知为已读
     */
    public boolean markConversationAsRead(String userId, String conversationId) {
        try {
            return notificationMapper.markConversationAsRead(userId, conversationId) >= 0;
        } catch (Exception e) {
            System.err.println("标记对话通知已读失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 手动创建通知（备用方案，当触发器不工作时）
     */
    public boolean createNotification(String userId, String userRole, String notificationType,
                                    String relatedId, String messageContent, String senderName) {
        try {
            NotificationStatusPojo notification = new NotificationStatusPojo(
                userId, userRole, notificationType, relatedId, messageContent, senderName
            );
            return notificationMapper.insertNotification(notification) > 0;
        } catch (Exception e) {
            System.err.println("创建通知失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 获取特定类型的未读通知数量
     */
    public int getUnreadCountByType(String userId, String notificationType) {
        try {
            return notificationMapper.getUnreadCountByType(userId, notificationType);
        } catch (Exception e) {
            System.err.println("获取特定类型未读通知数量失败: " + e.getMessage());
            return 0;
        }
    }

    /**
     * 检查是否有新通知（轮询优化）
     */
    public boolean hasNewNotificationsSince(String userId, LocalDateTime lastCheckTime) {
        try {
            String timeStr = lastCheckTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            return notificationMapper.hasNewNotificationsSince(userId, timeStr) > 0;
        } catch (Exception e) {
            System.err.println("检查新通知失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 获取最新通知时间
     */
    public String getLatestNotificationTime(String userId) {
        try {
            return notificationMapper.getLatestNotificationTime(userId);
        } catch (Exception e) {
            System.err.println("获取最新通知时间失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 清理旧通知
     */
    public int cleanOldNotifications(int days) {
        try {
            return notificationMapper.deleteOldNotifications(days);
        } catch (Exception e) {
            System.err.println("清理旧通知失败: " + e.getMessage());
            return 0;
        }
    }

    /**
     * 获取用户消息类型的未读通知数量（用于客服和用户的消息通知）
     */
    public int getMessageUnreadCount(String userId) {
        return getUnreadCountByType(userId, "new_message");
    }

    /**
     * 获取客服的新对话未读通知数量
     */
    public int getConversationUnreadCount(String userId) {
        return getUnreadCountByType(userId, "conversation_started");
    }

    /**
     * 标记消息通知为已读
     */
    public boolean markMessageNotificationsAsRead(String userId) {
        return markTypeAsRead(userId, "new_message");
    }

    /**
     * 标记对话通知为已读
     */
    public boolean markConversationNotificationsAsRead(String userId) {
        return markTypeAsRead(userId, "conversation_started");
    }
} 